<template>
  <div id="office">
    <div id="chart"
         :style="{height:height,width:width}" />
    <img id="img"
         src="~@/assets/office/office2.jpg"
         alt=""
         style="display:none"
         :style="{height:height,width:width}">
  </div>
</template>

<script>
import echarts from 'echarts'
import resize from './mixins/resize'
import { debounce } from '@/utils'
// import { Queue } from '@/utils'
import mapData from '@/constants/Map.constants'
import { isEqual } from '@/utils'

import { parseTime } from '@/utils'
// import { fetchList } from '@/api/data'

export default {
  mixins: [resize],
  // props:['id','show2D','tagId','width','height'],
  props: {
    // className: {
    //   type: String,
    //   default: 'chart'
    // },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '800px'
    },
    height: {
      type: String,
      default: '600px'
    },
    tagId: {
      type: String
    },
    show2D: {
      type: Boolean
    },
    tagInfo: {
      type: Array
    },
    tabsInfo: {
      type: Object
    },
    warningInfo: {
      type: Object
    },
    tagPosition: {
      type: Array
    }
  },
  data() {
    return {
      chart: null,
      img: new Image(), // 背景图片缓存
      img2: null, // 背景图片缓存
      img3: new Image(),
      canvas: null,
      ratio: null,
      imgSrc: require('@/assets/office/office2.jpg'),
      context: {}, // canvas对象
      axis: {
        startX: null,
        endX: null,
        startY: null,
        endY: null,
        symbolSize: 28
      },
      positionTracks: [],
      tagPosition_old: [],
      distance_queue: [],
      options: {
        backgroundColor: {
          image: null,
          repeat: 'no-repeat'
        },
        dataset: {
          dimensions: [],
          source: []
        },
        tooltip: {
          padding: 5,
          backgroundColor: '#222',
          borderColor: '#777',
          borderWidth: 1,
          formatter: function(obj) {
            console.log(obj)
            var value = obj.value
            if (
              obj.componentType === 'series' &&
              obj.dimensionNames.length === 5
            ) {
              return (
                '姓名' +
                '：' +
                value[2] +
                '<br>' +
                '标签ID' +
                '：' +
                value[3] +
                '<br>' +
                '类别' +
                '：' +
                value[4] +
                '<br>'
              )
            } else if (obj.dimensionNames.length === 3) {
              return '时间：' + value[2]
            }
          }
        },
        xAxis: {
          min: 0,
          max: mapData.mapWidth,
          // position:20,
          // offset:20,
          show: false //不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
          // axisTick: {
          //   show: false //不显示坐标轴刻度线
          // },
          // axisLine: {
          //   show: false //不显示坐标轴线
          // },
          // axisLabel: {
          //   show: false //不显示坐标轴上的文字
          // }
        },
        yAxis: {
          min: 0,
          max: mapData.mapHeight,
          show: false //不显示坐标轴线、坐标轴刻度线和坐标轴上的文字
          // axisTick: {
          //   show: false //不显示坐标轴刻度线
          // },
          // axisLine: {
          //   show: false //不显示坐标轴线
          // },
          // axisLabel: {
          //   show: false //不显示坐标轴上的文字
          // }
        },
        legend: {
          left: '2%',
          top: '2%',
          type: 'scroll',
          textStyle: {
            color: '#000',
            borderColor: '#324157',
            shadowColor: '#333',
            fontSize: 20,
            shadowBlur: 5,
            shadowOffsetX: 6,
            shadowOffsetY: 6
          }
        },
        grid: {
          x: '10%',
          y: '10%',
          x2: '10%',
          y2: '10%'
          // left: '10%',
          // bottom: '10%'
          // top: '10%',
          // right: '10%'
          // bottom:44,
          // top: '1%',
          // bottom: '2%'
        },
        dataZoom: [
          {
            id: 'dataZoomX',
            type: 'inside',
            throttle: 300,
            show: true,
            xAxisIndex: 0,
            start: 0,
            end: 100,
            minSpan: 28
          },
          {
            id: 'dataZoomY',
            type: 'inside',
            throttle: 300,
            show: true,
            yAxisIndex: 0,
            left: '93%',
            start: 0,
            end: 100,
            minSpan: 28
          },
          {
            type: 'slider',
            show: true,
            // throttle: 500,
            showDetail: false,
            xAxisIndex: 0,
            start: 0,
            end: 100,
            minSpan: 28
          },
          {
            type: 'slider',
            show: true,
            showDetail: false,
            // throttle: 500,
            yAxisIndex: 0,
            left: '5%',
            start: 0,
            end: 100,
            minSpan: 28
          }
        ],
        toolbox: {
          right: '2%',
          top: '2%',
          itemSize: 30,
          iconStyle: {
            borderColor: '#324157',
            borderWidth: 2.1,
            shadowColor: '#333',
            shadowBlur: 5,
            shadowOffsetX: 6,
            shadowOffsetY: 6
          },
          feature: {
            dataZoom: {
              show: true
              // xAxisIndex:true,
              // yAxisIndex:true,
            },
            saveAsImage: {}
          }
        },
        brush: {
          toolbox: ['rect', 'polygon', 'keep', 'clear'],
          throttleDelay: 500
        },
        series: []
      }
    }
  },
  mounted() {
    this.chart = echarts.init(document.getElementById(this.id))
    this.chart.showLoading()
    this.chart.setOption(this.options, true)
    document.getElementById('img').crossOrigin = 'anonymous'
    this.img.src = this.imgSrc
    this.img.width = '100%'
    this.img.height = '100%'
    this.canvas = document.createElement('canvas')
    this.context = this.canvas.getContext('2d')
    console.log(this.chart.getWidth())
    this.canvas.width = this.chart.getWidth()
    this.canvas.height = this.chart.getHeight()
    this.img2 = document.getElementById('img')
    this.img2.width = this.chart.getWidth()
    this.img2.height = this.chart.getHeight()
    this.ratio = devicePixelRatio
    this.options.backgroundColor.image = this.canvas
    this.img2.onload = () => {
      this.context.drawImage(
        this.img2,
        0,
        0,
        this.chart.getWidth(),
        this.chart.getHeight()
      )
      console.log(this.img2)
    }
    setTimeout(() => {
      let dataURL = this.canvas.toDataURL('image/png')
      // document.getElementById('img').src = dataURL
      this.img3.src = dataURL
      this.img3.onload = () => {
        if (devicePixelRatio >= 1) {
          this.canvas.width = this.chart.getWidth() * devicePixelRatio
          this.canvas.height = this.chart.getHeight() * devicePixelRatio
        } else {
          this.canvas.width = this.chart.getWidth() / devicePixelRatio
          this.canvas.height = this.chart.getHeight() / devicePixelRatio
        }
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
        this.context.drawImage(
          this.img3,
          this.chart.getWidth() * 0.1 * devicePixelRatio,
          this.chart.getHeight() * 0.1 * devicePixelRatio,
          this.canvas.width * 0.8,
          this.canvas.height * 0.8
        )
        this.chart.setOption(this.options)
        this.$nextTick(() => {
          this.chart.resize()
          this.chart.hideLoading()
          console.log(this.canvas.width)
        })
      }
    }, 2000)

    // this.$bus.on('showCharts', val => {
    //   console.log(val)
    //   this.chart.hideLoading()
    // })

    this.$_resizeHandler = this.handleResize()
    this.$_initResizeEvent()
    this.$_initSidebarResizeEvent()

    this.chart.on('datazoom', this.handledataZoomChanged)
    this.chart.on('brushSelected', this.handleBrushSelected)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  created() {},
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart.showLoading()
      this.chart.setOption(this.options, true)
    },
    handleResize() {
      let result = debounce(() => {
        if (this.show2D) {
          console.log(this.chart.getWidth())
          this.chart.resize()
          console.log(devicePixelRatio)
          this.$nextTick(() => {
            if (devicePixelRatio >= 1) {
              this.canvas.width = this.chart.getWidth() * devicePixelRatio
              this.canvas.height = this.chart.getHeight() * devicePixelRatio
            } else {
              this.canvas.width = this.chart.getWidth() / devicePixelRatio
              this.canvas.height = this.chart.getHeight() / devicePixelRatio
            }
            this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
            this.context.drawImage(
              this.img3,
              this.chart.getWidth() * 0.1 * devicePixelRatio,
              this.chart.getHeight() * 0.1 * devicePixelRatio,
              this.canvas.width * 0.8,
              this.canvas.height * 0.8
            )
            // this.chart.resize()
          })

          console.log(this.chart.getWidth())
          console.log(this.canvas.width)
        }
      }, 100)
      return result
    },
    createSeries(userName, x, y, color, tagId, userPost, status, buttonstatus) {
      let obj = {
        type: 'scatter',
        name: null,
        symbol:
          'path://M63.444 64.996c20.633 0 37.359-14.308 37.359-31.953 0-17.649-16.726-31.952-37.359-31.952-20.631 0-37.36 14.303-37.358 31.952 0 17.645 16.727 31.953 37.359 31.953zM80.57 75.65H49.434c-26.652 0-48.26 18.477-48.26 41.27v2.664c0 9.316 21.608 9.325 48.26 9.325H80.57c26.649 0 48.256-.344 48.256-9.325v-2.663c0-22.794-21.605-41.271-48.256-41.271z',
        symbolSize: 28,
        itemStyle: {
          color: color
          // normal: {
          //   opacity: 0.8
          // }
        },
        emphasis: {
          itemStyle: {
            borderWidth: 90,
            shadowColor: '#333',
            shadowBlur: 3
          }
        },
        dimensions: ['x', 'y', 'userName', 'tagId', 'userPost'],
        rippleEffect: { scale: 1.5 },
        markArea: {
          silent: true,
          data: [
            [{ coord: [15, 18] }, { coord: [28, 20] }],
            [{ coord: [28, 18] }, { coord: [26, 10] }]
          ],
          itemStyle: {
            color: '#333',
            opacity: 0.1
          }
        },
        markLine: {
          silent: true,

          data: [],
          symbol: 'none',
          lineStyle: {
            type: 'solid'
          }
        },
        data: []
      }
      if (userPost === '手推车') {
        obj.symbol =
          'path://M986.304 483.946667c-7.018667-13.248-20.416-20.522667-37.738667-20.522667h-0.042666l-642.88 0.554667a54.570667 54.570667 0 0 0-29.845334 8.938666L185.557333 168.341333a16 16 0 0 0-15.338666-11.477333H48.661333a16 16 0 0 0 0 32h109.610667l93.909333 317.013333a88.170667 88.170667 0 0 0 0.170667 49.450667l72.341333 253.034667c3.562667 12.501333 13.354667 23.04 25.92 29.674666l34.858667 117.696a16.042667 16.042667 0 0 0 27.093333 6.336l108.138667-116.949333 6.101333-0.021333a118.208 118.208 0 0 0-0.96 14.378666c0 65.6 53.354667 118.954667 118.954667 118.954667s118.954667-53.354667 118.954667-118.954667c0-6.122667-0.618667-12.117333-1.514667-18.005333 14.656-4.48 27.797333-14.421333 37.930667-29.397333l171.52-252.906667c19.413333-28.693333 24.746667-56.106667 14.613333-75.221333zM408.149333 919.68L386.133333 845.376l90.88-0.192-68.864 74.496z m236.629334 26.730667c-47.957333 0-86.954667-39.018667-86.954667-86.954667s38.997333-86.954667 86.954667-86.954667 86.954667 38.997333 86.954666 86.954667-38.997333 86.954667-86.954666 86.954667z m300.416-405.226667l-171.52 252.906667c-3.626667 5.354667-10.645333 13.333333-20.522667 16.576a119.04 119.04 0 0 0-108.373333-70.165334 119.146667 119.146667 0 0 0-109.525334 72.554667l-155.605333 0.32h-0.064c-11.562667 0-22.272-7.274667-24.128-13.802667l-72.341333-253.034666c-4.693333-16.405333-3.114667-32 4.181333-41.685334 4.437333-5.888 10.624-8.874667 18.368-8.896l642.88-0.554666h0.042667c7.573333 0 8.981333 2.666667 9.450666 3.541333 2.773333 5.269333 1.664 20.842667-12.842666 42.24z'
      }
      if (status === 1 || buttonstatus === 1) {
        obj.itemStyle.color = '#ff0000'
      } else {
        obj.itemStyle.color = color
      }
      obj.data = [[x, y, userName, tagId, userPost]]
      console.log(obj.data)
      obj.name = userName
      return obj
    },
    effectScatterChanged(obj) {
      console.log(obj)
    },
    handledataZoomChanged(params) {
      console.log(params)
      console.log(this.chart.getOption())
      this.axis.startX = this.chart.getOption().dataZoom[0].start / 100
      this.axis.endX = this.chart.getOption().dataZoom[0].end / 100
      this.axis.startY = this.chart.getOption().dataZoom[1].start / 100
      this.axis.endY = this.chart.getOption().dataZoom[1].end / 100
      this.axis.symbolSize = parseInt(
        (28 * mapData.mapWidth * mapData.mapHeight) /
          (this.chart.getOption().dataZoom[0].endValue -
            this.chart.getOption().dataZoom[0].startValue) /
          (this.chart.getOption().dataZoom[1].endValue -
            this.chart.getOption().dataZoom[1].startValue)
      )
      console.log(this.axis.symbolSize)
    },
    handleBrushSelected(params) {
      let brushed = []
      let brushComponent = params.batch[0]

      for (let sIdx = 0; sIdx < brushComponent.selected.length; sIdx++) {
        if (brushComponent.selected[sIdx].dataIndex.length != 0) {
          let rawIndices = brushComponent.selected[sIdx].seriesName
          brushed.push(rawIndices)
        }
      }
      this.$nextTick(() => {
        if (brushed.length != 0) {
          this.chart.setOption({
            title: {
              show: true,
              backgroundColor: '#333',
              text: '处在所选区域内的有: \n' + brushed.join('\n'),
              top: 50,
              left: 50,
              width: 100,
              textStyle: {
                fontSize: 26,
                color: '#fff'
              }
            }
          })
        } else {
          console.log(params)
          this.chart.setOption({
            title: {
              show: false
            }
          })
        }
      })
    },
    createTrackAnimation() {
      this.options.series.forEach(item => {
        this.$set(item.data[0], 0, 0)
        this.$set(item.data[0], 1, 0)
      })
      let obj = {
        type: 'scatter',
        name: 'Track',
        symbolSize: 6,
        itemStyle: {
          color: '#f00'
        },
        dimensions: ['x', 'y', 'time'],
        large: true,
        data: []
      }
      for (let i = 0; i < this.tabsInfo.positionTracks.length; i++) {
        this.positionTracks.push([
          this.tabsInfo.positionTracks[i][0] + mapData.mapWidth / 2,
          this.tabsInfo.positionTracks[i][1] + mapData.mapHeight / 2,
          parseTime(this.tabsInfo.positionTimes[i])
        ])
      }
      obj.data = this.positionTracks
      this.options.series.push(obj)
      this.$nextTick(() => {
        this.chart.setOption({ series: this.options.series })
      })
    },
    removeTrackAnimation() {
      this.positionTracks = []

      for (let i = 0; i < this.options.series.length; i++) {
        // console.log(this.options.series[i].name)
        if (this.options.series[i].name === 'Track') {
          console.log(this.options.series[i])
          this.options.series.pop()
          this.$nextTick(() => {
            this.chart.setOption(this.options, true)
          })
        }
      }
    }
  },
  watch: {
    'tabsInfo.positionTracks': {
      handler() {
        if (this.show2D) {
          if (this.positionTracks.length > 1) {
            this.removeTrackAnimation()
            this.createTrackAnimation()
          } else {
            console.log('2')

            this.createTrackAnimation()
          }
        }
      },
      deep: true
    },
    'tabsInfo.isSliderActive': function(val) {
      if (this.show2D) {
        if (val === false) {
          console.log('3')

          this.removeTrackAnimation()
        }
      }
    },
    tagPosition: {
      handler(newVal) {
        if (this.show2D && !this.tabsInfo.isSliderActive) {
          for (let i in this.tagPosition) {
            this.options.series[i].data[0][0] =
              this.tagPosition[i].position[0] + mapData.mapWidth / 2
            this.options.series[i].data[0][1] =
              this.tagPosition[i].position[1] + mapData.mapHeight / 2
            if (this.tagPosition_old.length > 0) {
              let dx = Math.abs(
                newVal[i].position[0] - this.tagPosition_old[i].position[0]
              )
              let dy = Math.abs(
                newVal[i].position[1] - this.tagPosition_old[i].position[1]
              )
              let distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2))
              if (this.distance_queue[i].length <= 4) {
                this.distance_queue[i].unshift(distance)
              } else {
                this.distance_queue[i].pop()
                this.distance_queue[i].unshift(distance)
              }
              let distance_change = () => {
                let sum = 0
                for (let j = 0; j < this.distance_queue[i].length; j++) {
                  sum = sum + this.distance_queue[i][j]
                }
                return sum > 0.2 ? true : false
              }
              let a = JSON.parse(
                JSON.stringify(this.tagPosition_old[i].position)
              )
              let b = JSON.parse(JSON.stringify(newVal[i].position))

              let coord = [
                {
                  coord: [
                    a[0] + mapData.mapWidth / 2,
                    a[1] + mapData.mapHeight / 2
                  ]
                },
                {
                  coord: [
                    b[0] + mapData.mapWidth / 2,
                    b[1] + mapData.mapHeight / 2
                  ]
                }
              ]
              if (distance_change()) {
                this.options.series[i].type = 'effectScatter'
                // this.options.series[i].rippleEffect.scale = 1.8
                this.options.series[i].symbolSize = this.axis.symbolSize + 2

                if (this.options.series[i].markLine.data.length <= 2) {
                  this.options.series[i].markLine.data.push(coord)
                } else {
                  this.options.series[i].markLine.data.shift()
                  this.options.series[i].markLine.data.push(coord)
                }
                console.log(this.options.series[i].data[0])
              } else {
                this.options.series[i].type = 'scatter'
                // this.options.series[i].rippleEffect.scale = 1.8
                this.options.series[i].symbolSize = this.axis.symbolSize
                if (this.options.series[i].markLine.data.length > 0) {
                  this.options.series[i].markLine.data.shift()
                }
              }
            }
          }
          this.tagPosition_old = JSON.parse(JSON.stringify(newVal))
          this.chart.setOption({ series: this.options.series })
        }
      },
      deep: true
    },
    tagInfo: {
      handler() {
        this.options.dataset.dimensions = Object.keys(this.tagInfo[0])
        this.options.dataset.source = this.tagInfo
        this.tagInfo.forEach(item => {
          this.options.series.push(
            this.createSeries(
              item.userName,
              0 + mapData.mapWidth / 2,
              0 + mapData.mapHeight / 2,
              item.color,
              item.tagId,
              item.userPost,
              item.status,
              item.buttonstatus
            )
          )
          this.distance_queue.push(new Array())
        })
      },
      deep: true
    },
    axis: {
      handler(axis) {
        if (devicePixelRatio >= 1) {
          this.canvas.width = this.chart.getWidth() * devicePixelRatio
          this.canvas.height = this.chart.getHeight() * devicePixelRatio
        } else {
          this.canvas.width = this.chart.getWidth() / devicePixelRatio
          this.canvas.height = this.chart.getHeight() / devicePixelRatio
        }
        this.chart.resize()
        this.$nextTick(() => {
          this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
          this.context.drawImage(
            this.img3,
            parseInt(this.img3.width * axis.startX),
            parseInt(this.img3.height * (1 - axis.endY)),
            parseInt(this.img3.width * (axis.endX - axis.startX)),
            parseInt(this.img3.height * (axis.endY - axis.startY)),
            this.chart.getWidth() * 0.1 * devicePixelRatio,
            this.chart.getHeight() * 0.1 * devicePixelRatio,
            this.canvas.width * 0.8,
            this.canvas.height * 0.8
          )
          // this.chart.resize()

          console.log(this.canvas.width)
        })
        // sy=1-ey ey=1-sy
        // this.chart.setOption({ series: this.options.series })

        //this.context.save()
      },
      deep: true
    },
    warningInfo: function(val, oldVal) {
      if (this.show2D) {
        let id = this.warningInfo.id
        if (!isEqual(val, oldVal)) {
          console.log(val)
          console.log(oldVal)
          for (let i = 0; i < this.options.series.length; i++) {
            if (id === this.options.series[i].data[0][3]) {
              if (this.warningInfo.status === 0) {
                this.options.series[i].itemStyle.color = this.tagInfo[i].color
                console.log(this.options.series[i].itemStyle.color)
              } else if (this.warningInfo.status === 1) {
                this.options.series[i].itemStyle.color = '#ff0000'
                console.log(this.options.series[i].itemStyle.color)
              } else if (this.warningInfo.status === 2) {
                this.options.series[i].itemStyle.color = '#ff0000'
              } else if (this.warningInfo.status === 3) {
                this.options.series[i].itemStyle.color = this.tagInfo[i].color
              } else if (this.warningInfo.status === 4) {
                this.options.series[i].itemStyle.color = '#ff0000'
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/mixin.scss';
@import '~@/styles/variables.scss';
// .map-container {
//   position: relative;
//   width: calc(100% - 54px);
//   height: calc(100vh + 25px);
// }
#office {
  // position: relative;
  margin: 0 auto;
  width: 100%;
  height: 100%;
}
// #chart {
//   background: url('~@/assets/office/office2.jpg') center no-repeat;
//   background-size: 80% 100%;
// }
</style>
